import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/class/announcementDto.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:reactive_dropdown_search/reactive_dropdown_search.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:get/get.dart';

class TeacherCreateAnnouncement extends StatelessWidget {
  static const String routeName = '/teacher/class/newannouncement';

  @override
  Widget build(BuildContext context) {
    Log.debug('build TeacherCreateAnnouncement');

    var box = Hive.box('appconfig');
    var classId = box.get(CacheManagerKey['currentclass'].toString());
    final SchoolAdminController _controller = Get.find();
    List<String> _students = [];
    _controller.fetchClassDetailsNewByClassId(classId);

    AnnouncementFormModel formModel = AnnouncementFormModel();
    var form = formModel.form;
    form.control('points').value = 0;
    form.control('allstudents').value = false;

    void _sendAnnouncementToStudents(ClassAnnouncementDto dto) async {
      _controller.sendClassAnnouncementsByClassId(classId, dto).then((result) {
        if (result.status == 1000) {
          showSnackMsg('Announcement has been sent successfully.');
          // Get.snackbar(
          //     'Message'.tr, 'Announcement has been sent successfully.'.tr,
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
          _controller.fetchClassAnnouncementsByClassId(classId);
          Future.delayed(Duration(seconds: 1),
              () => Navigator.pop(Get.context as BuildContext));
        } else {
          showSnackMsg('${result.message}');
          // Get.snackbar('Message'.tr, '${result.message}'.tr,
          //     backgroundColor: Theme.of(context).primaryColor,
          //     colorText: Theme.of(context).primaryColorLight,
          //     snackPosition: SnackPosition.BOTTOM);
        }
      });
    }

    return Scaffold(
      backgroundColor: Get.theme.primaryColor,
      appBar: CustomAppBar(title: 'Create Announcement'.tr),
      body: Obx(() {
        if (_controller.classDetailsNew.value.studentResps != null &&
            _controller.classDetailsNew.value.studentResps!.isNotEmpty) {
          _students = [];
          for (int i = 0;
              i < _controller.classDetailsNew.value.studentResps!.length;
              i++) {
            var usernamestring = _controller
                    .classDetailsNew.value.studentResps![i].userName
                    .toString() +
                ' - ' +
                _controller.classDetailsNew.value.studentResps![i].firstName
                    .toString() +
                ' ' +
                _controller.classDetailsNew.value.studentResps![i].lastName
                    .toString();
            _students.add(usernamestring);
          }

          return SingleChildScrollView(
            primary: false,
            child: Container(
              color: Colors.white.withOpacity(0.1),

              padding: const EdgeInsets.fromLTRB(100, 50, 100, 80),
              //margin: const EdgeInsets.fromLTRB(100, 100, 100, 0),
              child: Center(
                child: ReactiveForm(
                  formGroup: form,
                  child: Column(
                    children: <Widget>[
                      Row(
                        children: [
                          Text(
                            _controller.classDetailsNew.value.className
                                .toString(),
                            style: Theme.of(context).textTheme.titleLarge,
                          ),
                          SizedBox(
                            width: 5,
                          ),
                          Text(
                            '(Class ID: ${_controller.classDetailsNew.value.classId.toString()})',
                            style: Theme.of(context).textTheme.bodyLarge,
                          ),
                        ],
                      ),
                      ReactiveCheckboxListTile(
                        formControlName: 'allstudents',
                        title: Text(
                          'All Students?'.tr,
                          style: Theme.of(context).textTheme.displaySmall,
                        ),
                        subtitle: Text(
                          'If selected, announcement will be sent to all students in the class.'
                              .tr,
                          style: Theme.of(context).textTheme.labelSmall,
                        ),
                      ),
                      SizedBox(
                        height: 12,
                      ),
                      ReactiveValueListenableBuilder<bool>(
                        formControlName: 'allstudents',
                        builder: (context, control, child) {
                          Log.debug(
                              'allstudents listen control.value=${control.value}');
                          return Visibility(
                              visible: !(control.value ?? false),
                              child: Column(
                                children: [
                                  ReactiveDropdownSearchMultiSelection<String,
                                      String>(
                                    //popupBackgroundColor: Colors.white,
                                    formControlName: 'students',
                                    dropdownDecoratorProps:
                                        DropDownDecoratorProps(
                                      dropdownSearchDecoration: InputDecoration(
                                        hintText: "Select students".tr,
                                        labelText: "Students".tr,
                                      ),
                                    ),
                                    // decoration:  InputDecoration(
                                    //   hintText: "Select students".tr,
                                    //   labelText: "Students".tr,
                                    //   helperText: '',
                                    // ),
                                    //popupBackgroundColor: Colors.white,
                                    popupProps: PopupPropsMultiSelection.menu(
                                        showSelectedItems: true,
                                        showSearchBox: true),
                                    //mode: Mode.DIALOG,
                                    //showSearchBox: true,
                                    //showSelectedItems: true,
                                    items: _students,
                                    //label: "Select Students",
                                    showClearButton: true,
                                    //maxHeight: 450,
                                  ),
                                ],
                              ));
                        },
                      ),
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.1),
                        ),
                        child: ReactiveTextField(
                          formControlName: 'message',
                          style: Theme.of(context).textTheme.displaySmall,
                          maxLines: 5,
                          //textInputAction: TextInputAction.next,
                          decoration: InputDecoration(
                            alignLabelWithHint: true,
                            labelText: 'Message'.tr,
                            labelStyle:
                                Theme.of(context).textTheme.displaySmall,
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 12,
                      ),
                      ReactiveTextField(
                        formControlName: 'points',
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly
                        ],
                        // Only numbers can be entered
                        //textInputAction: TextInputAction.next,
                        style: Theme.of(context).textTheme.bodyLarge,
                        decoration: InputDecoration(
                          labelText: 'Points'.tr,
                          labelStyle: Theme.of(context).textTheme.displaySmall,
                          helperText:
                              'Students will get these points when they read the announcement.'
                                  .tr,
                          helperStyle: Theme.of(context).textTheme.labelSmall,
                        ),
                      ),
                      SizedBox(
                        height: 12,
                      ),
                      ReactiveFormConsumer(
                        builder: (context, form, child) {
                          ClassAnnouncementDto dto = new ClassAnnouncementDto();
                          if (form.control('allstudents').value == false) {
                            dto.allStudentsClass = false;
                            if (form.control('students').value != null) {
                              List<String> _selectedStudents =
                                  form.control('students').value;
                              if (_selectedStudents.length > 0) {
                                List<String> _namelist = [];
                                _selectedStudents.forEach((element) {
                                  int start = element.indexOf(' - ');
                                  var tempstr = element.substring(0, start);

                                  if (!_namelist.contains(tempstr))
                                    _namelist.add(tempstr);
                                });
                                dto.studentUserName = _namelist;
                              } else {
                                dto.studentUserName = [];
                              }
                            }
                          } else {
                            dto.allStudentsClass = true;
                          }
                          dto.message = form.control('message').value;
                          dto.point = form.control('points').value.toString();
                          return ElevatedButton(
                              style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all<Color>(
                                        Theme.of(context).primaryColorDark),
                                foregroundColor:
                                    MaterialStateProperty.all<Color>(
                                        Theme.of(context).primaryColorLight),
                              ),
                              child: Text('Submit'.tr),
                              onPressed: () {
                                Log.debug(
                                    "form.valid=${form.valid} form.value=${form.value}");

                                if (!form.valid) {
                                  form.markAllAsTouched();
                                  return;
                                }

                                if (dto.allStudentsClass == false &&
                                    dto.studentUserName?.length == 0) {
                                  showSnackMsg(
                                      'Please select at least one student');
                                  // Get.snackbar('Message'.tr,
                                  //     'Please select at least one student'.tr,
                                  //     backgroundColor:
                                  //         Theme.of(context).primaryColor,
                                  //     colorText:
                                  //         Theme.of(context).primaryColorLight,
                                  //     snackPosition: SnackPosition.BOTTOM);
                                  return;
                                } else if (form.control('points').value >
                                    1000) {
                                  showSnackMsg(
                                      'Announcement Point range should be within 0 - 1000');
                                  // Get.snackbar(
                                  //     'Message'.tr,
                                  //     'Announcement Point range should be within 0 - 1000'
                                  //         .tr,
                                  //     backgroundColor:
                                  //         Theme.of(context).primaryColor,
                                  //     colorText:
                                  //         Theme.of(context).primaryColorLight,
                                  //     snackPosition: SnackPosition.BOTTOM);
                                  return;
                                } else {
                                  _sendAnnouncementToStudents(dto);
                                }
                              });
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          );
        } else {
          return Text('Please add students to the class first!'.tr);
        }
      }),
    );
  }
}
